package main

import (
    "fmt"
    "github.com/emicklei/go-restful"
    "log"
    "net/http"
)

type User struct {
    Id      string `json:"id" valid:"-"`
    Name    string `json:"name" valid:"-"`
    Old     string `json:"old" valid:"-"`
}

func New() *restful.WebService {
    service := new(restful.WebService)
    service.
        Path("/users").
        Consumes(restful.MIME_JSON).
        Produces(restful.MIME_JSON)

    service.Route(service.GET("/{user-id}").To(FindUser))
    service.Route(service.POST("").To(UpdateUser))
    service.Route(service.PUT("/{user-id}").To(CreateUser))
    service.Route(service.DELETE("/{user-id}").To(RemoveUser))

    return service
}

func FindUser(request *restful.Request, response *restful.Response) {
    name := request.QueryParameter("name")
    // here you would fetch user from some persistence system
    fmt.Println("----1")
    fmt.Println(name)
    usr1 := new(User)
    //usr1.Id = id
    usr1.Name = name
    request.ReadEntity(&usr1)
    //usr := &User{Id: id, Name: "John Doe"}
    response.WriteEntity(&usr1)
}

func UpdateUser(request *restful.Request, response *restful.Response) {
    name := request.QueryParameter("name")
    array := []string{name}
    fmt.Println(array)
    usr := new(User)
    usr.Name = name
    //err := request.ReadEntity(&usr)
    // here you would update the user with some persistence system
    //if err == nil {
    response.WriteEntity(usr)
    //} else {
    //    response.WriteError(http.StatusInternalServerError,err)
    //}
}

func CreateUser(request *restful.Request, response *restful.Response) {
    usr := User{Id: request.PathParameter("user-id")}
    err := request.ReadEntity(&usr)
    // here you would create the user with some persistence system
    if err == nil {
        response.WriteEntity(usr)
    } else {
        response.WriteError(http.StatusInternalServerError,err)
    }
}

func RemoveUser(request *restful.Request, response *restful.Response) {
    // here you would delete the user from some persistence system
}


func main() {
    restful.Add(New())
    log.Fatal(http.ListenAndServe(":8080", nil))
}
